# == Schema Information
#
# Table name: base_notices
#
#  id          :integer          not null, primary key
#  from        :integer
#  to          :integer
#  status      :integer          default(0)
#  notice_type :integer          default(0)
#  title       :string(255)
#  content     :string(255)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class Base::Notice < ApplicationRecord
  belongs_to :sender, class_name: 'User', foreign_key: 'from', optional: true
  belongs_to :receiver, class_name: 'User', foreign_key: 'to', optional: true

  scope :received, -> { where(to: Base::User.current&.id) }
  scope :sent, -> { where(from: Base::User.current&.id) }

  scope :unread, -> { where(status: STATUS[:unread]) }
  scope :readed, -> { where(status: STATUS[:readed]) }
  scope :deleted, -> { where(status: STATUS[:deleted]) }

  STATUS = {unread: 0, readed: 1, deleted: 2}
  NOTICE_TYPE = {system: 0}

  extend Enumerize
  enumerize :notice_type, in: NOTICE_TYPE, predicates: { prefix: true }, scope: true
  enumerize :status, in: STATUS, predicates: { prefix: true }, scope: true

  def read!
    update(status: STATUS[:readed]) if self.status_unread?
  end

  def delete!
    update(status: STATUS[:deleted]) if self.status_unread? || self.status_readed?
  end

  class << self
    def send_message **args
      options = {
          title: '系统通知',
          from: nil,
          notice_type: NOTICE_TYPE[:system],
          status: STATUS[:unread]
      }
      options.update(args)
      return nil if options[:to].blank?

      receivers = get_receives(options[:to])

      receivers.compact.each do |to|
       self.create(
          to: to,
          from: options[:from],
          status: options[:status],
          notice_type: options[:notice_type],
          title: options[:title],
          content: options[:content]
      )
      end

    end

    def get_receives to
      if to.is_a?(Array)
        to.map! do |t|
          if t.is_a?(::Base::User)
            t.id
          elsif t.is_a?(String)
            User.find_by_name(t).try(:id)
          else
            t
          end
        end
      elsif to.is_a?(::Base::User)
        to = [to.id]
      elsif to.class.to_s == "Base::User::ActiveRecord_Relation"
        to = to.map(&:id)
      elsif to.is_a?(String)
        to = [::Base::User.find_by_username(to).try(:id)]
      elsif to.is_a?(Symbol)
        to = get_group(to).map(&:id)
      elsif to.is_a?(Customer)
        to = to.users.map(&:id)
      else
        to = [to]
      end
      to
    end

    def get_group symbol
      {
         #todo...
      }[symbol]
    end
  end

end
